#region Using directives

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Hosting;

#endregion

namespace CustomWorkflowActivitiesTestApplication
{
    class Program
    {
        public const int WORKFLOW_COUNT = 10;
        public const int LOOP_COUNT = 10;

        public static String Current = "";
        public static int Count = 0;

        static int numberOfWorkflowInstances = WORKFLOW_COUNT;
        public static object guard = new object();

        static void Main(string[] args)
        {
            using (WorkflowRuntime workflowRuntime = new WorkflowRuntime())
            {
                workflowRuntime.AddService(new CustomWorkflowActivities.SynchronizationService(workflowRuntime));
                AutoResetEvent waitHandle = new AutoResetEvent(false);
                workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e)
                {
                    lock (guard)
                    {
                        if (--numberOfWorkflowInstances == 0)
                        {
                            waitHandle.Set();
                        }
                    }
                };

                workflowRuntime.WorkflowTerminated += delegate(object sender, WorkflowTerminatedEventArgs e)
                {
                    Console.WriteLine(e.Exception.Message);
                    lock (guard)
                    {
                        if (--numberOfWorkflowInstances == 0)
                        {
                            waitHandle.Set();
                        }
                    }
                };

                int count = numberOfWorkflowInstances;
                Dictionary<string, object> workflowArgs = new Dictionary<string, object>();
                workflowArgs.Add("InstanceName", 0);
                for (int i = 0; i < count; i++)
                {
                    workflowArgs["InstanceName"] = i;
                    WorkflowInstance instance = workflowRuntime.CreateWorkflow(typeof(CustomWorkflowActivitiesTestApplication.TestsRealSynchronizationScope), workflowArgs);
                    instance.Start();
                }

                waitHandle.WaitOne();
                if (!Current.Equals(""))
                {
                    throw new Exception();
                }
                if (Count != WORKFLOW_COUNT * LOOP_COUNT - 4)
                {
                    throw new Exception();
                }
                Console.WriteLine("done");
                Console.ReadKey();
            }
        }
    }
}
